package com.moduleSys.menuService;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moduleSys.config.RedisConfig;
import com.moduleSys.entity.system.Menu;
import com.moduleSys.entity.system.MenuVo;
import com.moduleSys.entity.system.User;
import com.moduleSys.mapper.MenuMapper;
import com.moduleSys.mapper.RoleMenuMapper;
import com.moduleSys.utils.json.JsonResult;
import com.moduleSys.utils.json.SerializeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

/**
 * Created by czw on 2017/7/19 0019.
 */
@Service
public class MenuService {

    private static final String MENU_REDIS_KEY = "menu_redis_list";

    /**
     * @TODO 左边菜单集合使用redis存储失效时间为 1 天，开发时应尽量设置小点
     */
    private static final int SECONDS = 60 * 60 * 24;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private static RedisConfig redisConfig;
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    public Menu insert(Menu res) {
        menuMapper.insert(res);
        return res;
    }

    public JsonResult selectByMap(Integer pageSize, Integer currentPage, String name) {
        JsonResult jr = new JsonResult();
        PageHelper.startPage(currentPage, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        List<Menu> menus = menuMapper.selectByMap(map);
        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        long total = pageInfo.getTotal();
        List<Menu> list = pageInfo.getList();
        jr.setData(list);
        jr.setNumber(total);
        return jr;
    }

    public List<Menu> getMenuByRoleId(Long roleId) {
        List<Menu> list = menuMapper.getMenuByRoleId(roleId);
        return list;
    }

    public List<MenuVo> getAuthorizationMenu() {
        System.out.println("测试》》》 "+redisConfig);
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getSession().getAttribute("user");

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Menu> menuList = null;
        if (jedis != null) {
            byte[] menuBytes = jedis.get(SerializeUtils.serialize(MenuService.MENU_REDIS_KEY));
            if (StringUtils.isEmpty(menuBytes)) {
                menuList = menuMapper.getAuthorizationMenu(user.getId());
                jedis.setex(SerializeUtils.serialize(MenuService.MENU_REDIS_KEY), MenuService.SECONDS, SerializeUtils.serialize(menuList));
            } else {
                menuList = (List<Menu>) SerializeUtils.unserialize(menuBytes);
            }
            jedisPool.returnResource(jedis);
        } else {
            menuList = menuMapper.getAuthorizationMenu(user.getId());
        }

        List<MenuVo> menuVoList = new ArrayList<>();
        List<MenuVo> list = new ArrayList<>();
        for (int i = 0; i < menuList.size(); i++) {
            MenuVo menuVo = new MenuVo();
            menuVo.setPid(menuList.get(i).getId() + "");
            menuVo.setHref(menuList.get(i).getResUrl());
            menuVo.setIcon(menuList.get(i).getIcon());
            menuVo.setTitle(menuList.get(i).getName());
            list = this.getChildNodes(menuList, menuList.get(i), new ArrayList());
            if (list.size() > 0) {
                menuVo.setChildren(list);
            }
            if (menuList.get(i).getParentId() == 0) {
                menuVoList.add(menuVo);
            }

        }
        return menuVoList;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, Exception.class})
    public JsonResult deleteBatch(Long[] itemIds) {
        if (itemIds != null && itemIds.length > 0) {
            menuMapper.deleteBatchById(itemIds);
            List<Long> list = new ArrayList<>();
            for (long menuId : itemIds) {
                list.add(menuId);
            }
            roleMenuMapper.deleteBatchByMenuId(list);
            return new JsonResult(1, null, null);
        } else {
            return new JsonResult(0, null, null);
        }
    }

    public JsonResult updateMenu(Menu menu) {
        menuMapper.updateByPrimaryKey(menu);
        return new JsonResult(1, null, null);
    }

    private List getChildNodes(List<Menu> list, Menu Menu, List returnList) {
        for (Iterator<Menu> iterator = list.iterator(); iterator.hasNext(); ) {
            Menu node = (Menu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (Menu.getId().equals(node.getParentId())) {
                MenuVo menuVos = new MenuVo();
                menuVos.setPid(node.getId() + "");
                menuVos.setHref(node.getResUrl());
                menuVos.setIcon(node.getIcon());
                menuVos.setTitle(node.getName());
                returnList.add(menuVos);
                //递归遍历子后子
                getChildNodes(list, node, returnList);
            }
        }
        return returnList;
    }
}
